package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video/model/cache"
	"video/model/mysql"
	"video/pkg"

	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result == "" {
		return nil, errors.New("当前未发送短信验证码")
	}
	if result != in.SendSms {
		return nil, errors.New("当前短信验证码错误，请重新输入")
	}

	var findUser mysql.User
	err := findUser.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if findUser.ID != 0 {
		return nil, errors.New("该手机号已注册，可直接登录")
	}

	user := &mysql.User{
		Phone:     in.Mobile,
		Password:  pkg.Md5Str(in.Password),
		NickName:  fmt.Sprintf("游客_%d", rand.Intn(10000)),
		HeadImage: "http://t4kajnapy.hn-bkt.clouddn.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250904204140_172_44.jpg",
		Status:    int(in.Status),
		FollowNum: int(in.FollowNum),
		FansNum:   int(in.FansNum),
	}
	err = user.Register(mysql.DB)
	if err != nil {
		return nil, errors.New("用户注册失败")
	}

	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
